import { useHistory, useLocation } from 'react-router-dom'
import { InfiniteScroll, NavBar } from 'antd-mobile'

import styles from './index.module.scss'
import { useDispatch, useSelector } from 'react-redux'
import { useEffect, useState } from 'react'
import { getSearchResults } from '@/store/actions/search'
import { RootAction, RootState } from '@/types/store'
import ArticleItem from '@/pages/Home/ArticleItem'

const Result = () => {
  const history = useHistory()
  const location = useLocation()
  console.log('location', location)
  const keyword = new URLSearchParams(location.search).get('keyword')
  console.log('keyword', keyword)

  const dispatch = useDispatch()

  // useEffect(() => {
  //   dispatch(getSearchResults(keyword!, 1))
  // }, [dispatch, keyword])

  // todo 获取仓库中的搜索结果数据
  const { results } = useSelector((state: RootState) => state.search)

  const [page, setPage] = useState(1)

  // 问题: 搜索js 出现搜索结果: 搜索vue 出现的搜索结果和上次搜索的结果是一样的
  // 分析: 搜索结果页用的是仓库中的数据, 退出搜索结果页后并没有清空仓库中的数据
  // 解决: 退出搜索结果页面时, 清空仓库数据!!!
  useEffect(() => {
    return () => {
      // 清空仓库数据
      dispatch({
        type: 'search/clear_results',
      } as RootAction)
    }
  }, [dispatch])

  return (
    <div className={styles.root}>
      <NavBar onBack={() => history.go(-1)}>搜索结果</NavBar>
      <div className="article-list">
        {results.map((item, index) => {
          return (
            <div
              className="article-item"
              key={item.art_id}
              onClick={() => {
                history.push('/article/' + item.art_id)
              }}
            >
              <ArticleItem article={item} type={item.cover.type}></ArticleItem>
            </div>
          )
        })}

        <InfiniteScroll
          /* 根据后端返回的数据total_count 135 然后超过了这个条数 results.length 就停止加载 */
          hasMore={true}
          loadMore={async () => {
            await dispatch(getSearchResults(keyword!, page))
            setPage(page + 1)
          }}
        ></InfiniteScroll>
      </div>
    </div>
  )
}

export default Result
